/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.struts.User.NewUser;

import com.myapp.model.estados.Estados;
import com.myapp.model.lenguajes.Lenguajes;
import com.myapp.model.nivel.Nivel;
import com.myapp.model.usuaLeng.Usualeng;
import com.myapp.model.usuarios.Usuarios;
import com.myapp.svc.User.UserSvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Jaime
 */
public class NewUserAction extends org.apache.struts.action.Action {

    /*
     * forward name="success" path=""
     */
    private static final String SUCCESS = "success";
    private static final String ERROR = "error";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward result = null;
        Usuarios usr = new Usuarios();
        Usuarios usr2 = new Usuarios();
        UserSvc usrSvc = new UserSvc();
        Usualeng usuaLeng=new Usualeng();
        Lenguajes leng=new Lenguajes();
        Nivel niv=new Nivel();
        usr.setEmail(((NewUserForm) form).getEmail());
        usr = usrSvc.search(usr);

        /*
         * El email no existe por lo que puede registrarse comprobar tambien alias??
         */
        if (usr == null) {
            HttpSession session=request.getSession();
            usr = new Usuarios();
            
            Estados est=new Estados();
            byte b=2;
            est.setIdestado(b);
            boolean newUser=true;
            
            usr.setAlias(((NewUserForm)form).getLogin());
            usr.setPassword(((NewUserForm)form).getPassword());
            usr.setNombre(((NewUserForm) form).getName());
            usr.setApellidos(((NewUserForm) form).getSurname());
            usr.setEmail(((NewUserForm) form).getEmail());
            usr.setEstados(est);
            usr.setDispcorregir((byte)5);
            
            usr=usrSvc.newOrUpdateUser(usr,usr2,newUser);
            
            leng.setIdlenguaje(Integer.valueOf(1));
            usuaLeng.setLenguajes(leng);
            niv.setIdnivel(Integer.valueOf(1));
            usuaLeng.setNivel(niv);
            usuaLeng.setUsuarios(usr);
            usrSvc.darnivel(usuaLeng);
            session.setAttribute("usuarios", usr);
            result = mapping.findForward(SUCCESS);
        } else {
            result = mapping.findForward(ERROR);
        }


        return result;
    }
}
